import cTitle from "components/title";
import yzGoodsPopup from "components/ui_components/yz_goodsPopup";
import yzSpecs from "components/ui_components/yz_specs"
import { Toast } from 'vant';
// import fun from "../../fun";

export default {
  data() {
    return {
      //套餐ID
      package_id: "",
      carousels: [],
      packageTitle: "",
      description_title: "",
      description_thumb: "",
      description_desc: "",
      category_idex: 0,
      categories: [],
      vanShow: false,
      zongjiage: 0.0,
      other_packages: [],
      categoriesArrTop: [],
      categoriesheight: [],
      mainInfo: {
        name: "",
        thumb: "",
        introduce: ""
      },
      //显示购结束时间
      limit_time_status: false,
      endTime: 0,
      endTimeStr: "",
      on_sale_price: 0,
      sale_priceshow: false,
      clientWidths: "",
      salePrice:0,
      page_template: 0,
      goodsIdsArr:[], //选中的ID
      showgp: false,//商品详情弹窗
      //优化
      popupSpecs:false,
      goodData:{},
      optionId:''
    };
  },
  activated() {
    this.package_id = this.$route.params.id;
    //获取套餐数据
    this.getpackage();
    window.addEventListener("scroll", this.slider);
    this.clientWidths = document.body.clientWidth;
  },
  methods: {
    getpackage() {
      $http
        .get(
          "plugin.goods-package.frontend.package.package.index",
          {
            package_id: this.package_id
          },
          "添加中..."
        )
        .then(response => {
          if (response.result == 1) {
            this.getShareData(response.data);
            this.carousels = response.data.carousels;
            this.packageTitle = response.data.title;
            this.description_thumb = response.data.description_thumb;
            this.description_title = response.data.description_title;
            this.description_desc = response.data.description_desc;
            this.page_template = response.data.page_template||0;
            this.categories = response.data.categories;
            this.other_packages = response.data.other_packages;
            this.on_sale_price = parseFloat(response.data.on_sale_price);
            this.limit_time_status =
              response.data.limit_time_status == 1 ? true : false;
            this.endTime = new Date(parseInt(response.data.end_time) * 1000);
            this.endTimeStr = String(this.endTime);
            for (let i = 0; i < this.categories.length; i++) {
              // this.categories[i].categyd_id=[];
              for (let j = 0; j < this.categories[i].goods_list.length; j++) {
                this.$set(
                  this.categories[i].goods_list[j],
                  "popPrice",
                  this.categories[i].goods_list[j].price
                ); //动态添加
                this.$set(this.categories[i].goods_list[j], "popThumb", ""); //动态添加
                this.$set(this.categories[i].goods_list[j], "goodsnum", 1); //动态添加
                this.$set(this.categories[i].goods_list[j], "optionsId", ""); //动态添加
                this.$set(this.categories[i].goods_list[j], "specsManage", []); //动态添加
                this.$set(
                  this.categories[i].goods_list[j],
                  "popStock",
                  this.categories[i].goods_list[j].stock
                ); //动态添加
                this.$set(this.categories[i].goods_list[j], "checked", false); //动态添加
                // this.categories[i].goods_list[j].popPrice=this.categories[i].goods_list[j].market_price;
                // this.categories[i].goods_list[j].popThumb='';
                // this.categories[i].goods_list[j].goodsnum=1;
                // this.categories[i].goods_list[j].optionsId="";
                // this.categories[i].goods_list[j].specsManage=[];
                // this.categories[i].goods_list[j].popStock=this.categories[i].goods_list[j].stock;
                // this.categories[i].goods_list[j].checked=true;

                if(this.page_template) {
                  this.categories[i].goods_list[j].checked=true;//默认选择
                  //new add
                  if(this.categories[i].goods_list[j].has_option){//默认选择第一个
                    this.categories[i].goods_list[j].optionsId=this.categories[i].goods_list[j].has_many_options[0].id;
                  }
                }

                for (
                  let k = 0;
                  k < this.categories[i].goods_list[j].has_many_specs.length;
                  k++
                ) {
                  this.$set(
                    this.categories[i].goods_list[j].has_many_specs[k],
                    "speshow",
                    ""
                  ); //动态添加
                  // this.categories[i].goods_list[j].has_many_specs[k].speshow="";
                  for (
                    let d = 0;
                    d <
                    this.categories[i].goods_list[j].has_many_specs[k].specitem
                      .length;
                    d++
                  ) {
                    this.$set(
                      this.categories[i].goods_list[j].has_many_specs[k]
                        .specitem[d],
                      "dispec",
                      false
                    ); //动态添加
                    if(this.page_template) this.categories[i].goods_list[j].has_many_specs[k].specitem[d].dispec=false;
                  }
                }
              }
            }

            if(this.page_template){
              this.calculateGooss();
              if (typeof response.data.recharge_code != 'undefined') {
                this.recharge_code = response.data.recharge_code;
              }
            }
          } else {
            Toast(response.msg);
            this.$router.push(this.fun.getUrl("home", {}));
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    goodsSpescOn(item) {
      this.popupSpecs = true;
      this.goodData = item;
      console.log(this.goodData);
      this.optionId = item.has_many_options[0].id;
    },
    async getSalePrice() {
       let res = await $http.post(
          "plugin.goods-package.frontend.package.package.get-sale-price",
          {
            package_id: Number(this.package_id),
            goods_ids:this.goodsIdsArr
          },
          "添加中..."
        );
        if (res.result == 1) {
          let data = res.data;
          this.salePrice = parseFloat(data.on_sale_price);
        } else {
          Toast(res.msg);
          this.$router.push(this.fun.getUrl("home", {}));
        }
    },
    /*项目瞄点*/
    categoriesbtn(e) {
      console.log(e);
      let index = e;
      let anchor = this.$el.querySelector("#cate_" + index);
      let categoryheight = this.$el.querySelector("#categoryhei").offsetHeight;
      this.$nextTick(() => {
        document.body.scrollTop = anchor.offsetTop - categoryheight;
        document.documentElement.scrollTop = anchor.offsetTop - categoryheight;
      });
      this.category_idex = index;
    },
    /*项目总标题随滚动条变换显示方式*/
    slider(e) {
      if(this.page_template) return;
      this.categoriesArrTop = [];
      this.categoriesheight = [];
      let content_ahei = this.$el.querySelector(".content_a")?.offsetHeight;
      let bannerHeight = this.$refs.banner?.offsetHeight;
      // let content_bhei = this.$el.querySelector(".content_b").offsetHeight;
      let headerMain = this.$refs.headerMain?.offsetHeight;
      let top = document.documentElement.scrollTop || document.body.scrollTop;
      if (top < headerMain + content_ahei + bannerHeight) {
        this.vanShow = false;
      } else {
        console.log('')
        this.vanShow = true;
      }
      for (let b = 0; b < this.categories.length; b++) {
        let anchor = this.$el.querySelector("#cate_" + b);
        let categoryheight = this.$el.querySelector("#categoryhei")
          .offsetHeight;
        this.categoriesArrTop.push(anchor.offsetTop - categoryheight);
        this.categoriesheight.push(anchor.offsetHeight);
      }
      for (let k = 0; k < this.categoriesArrTop.length; k++) {
        if (
          top >= this.categoriesArrTop[k] &&
          this.categoriesArrTop[k] + this.categoriesheight[k] >= top
        ) {
          this.category_idex = k;
        }
      }
    },
    close_yz_specs_popup(_optionsId, goodsCount, clicktype) {
      this.popupSpecs = false;
      if(clicktype === 1) {
        this.categories.forEach((item,index) => {
          item.goods_list.forEach((goodsItem,goodsIndex) => {
            goodsItem.has_many_options.forEach((optionItem,optionIndex) => {
              if(optionItem.id === _optionsId) {
                goodsItem.popStock = optionItem.stock;
                goodsItem.goodsnum = goodsCount;
                goodsItem.optionsId = _optionsId;
                goodsItem.popPrice = optionItem.product_price;
                this.$set(goodsItem, 'optionName',optionItem.title);
              }
            })
          })
        });
      }

    },
    //计算商品价格
    calculateGooss: function() {
      let pic = 0;

      for (let i = 0; i < this.categories.length; i++) {
        for (let j = 0; j < this.categories[i].goods_list.length; j++) {
          if (this.categories[i].goods_list[j].checked) {
            let goodsnum = this.categories[i].goods_list[j].goodsnum;
            let popPrice = this.categories[i].goods_list[j].popPrice;

            pic += goodsnum * popPrice;
          }
        }
      }
      if (pic && this.on_sale_price && this.sale_priceshow) {
        pic = pic - this.on_sale_price;
      } else {
        if(pic && this.salePrice) { //显示优化的价格
          pic = pic - this.salePrice;
        }
      }
      if(pic>0) {
        this.zongjiage = pic.toFixed(2);
      }else {
        this.zongjiage = 0;
      }
    },
    addnum: function() {
      this.calculateGooss();
    },
    categydbtn: async function() {
      let goodsIdsArr = [];
      if (this.limit_time_status) {
        let checkedBol = [];
        for (let i = 0; i < this.categories.length; i++) {
          for (let j = 0; j < this.categories[i].goods_list.length; j++) {
            if (this.categories[i].goods_list[j].checked) {
              checkedBol.push(i);
              goodsIdsArr.push(this.categories[i].goods_list[j].id);
              break;
            }
          }
        }
        if (this.categories.length == checkedBol.length) {
          this.sale_priceshow = true;
        } else {
          this.sale_priceshow = false;
        }
      } else {
        for (let i = 0; i < this.categories.length; i++) {
          for (let j = 0; j < this.categories[i].goods_list.length; j++) {
            if (this.categories[i].goods_list[j].checked) {
              goodsIdsArr.push(this.categories[i].goods_list[j].id);
            }
          }
        }
      }

      this.goodsIdsArr = goodsIdsArr;

      await this.getSalePrice();
      this.calculateGooss();

    },
    //提交订单
    submitGoods() {
      let goodBol = true;
      let json = {};
      var _cart_ids = [];
      json.package_id = this.package_id;
      json.goods_list = [];
      for (let i = 0; i < this.categories.length; i++) {
        for (let j = 0; j < this.categories[i].goods_list.length; j++) {
          let goods_list = this.categories[i].goods_list;
          let json_1 = {};
          if (
            goods_list[j].has_option == 1 &&
            (goods_list[j].checked &&
              (!goods_list[j].optionsId &&
                goods_list[j].has_many_specs.length > 0))
          ) {
            Toast("请选择商品规格");
            return false;
          }
          if (goods_list[j].checked) {
            goodBol = false;
            _cart_ids.push(goods_list[j].id);
            json_1.goods_id = goods_list[j].id;
            json_1.option_id = goods_list[j].optionsId;
            json_1.total = goods_list[j].goodsnum;
            json.goods_list.push(json_1);
          }
        }
      }
      console.log(json);
      if (goodBol) {
        Toast("请选择结算商品");
        return false;
      }

      this.$router.push(
        this.fun.getUrl("goodsorder",{
          packagJson: json,
        }, {
          tag: "packagBuy",
          goods_ids: JSON.stringify(_cart_ids)
        })
      );
    },
    //跳到商品详情
    gogoodsDetailBtn: function(goodsid) {
      if(this.page_template) return;
      this.$router.push(this.fun.getUrl("goods", { id: goodsid },{buybtn: 'not'}));
    },
    //跳到套餐
    gopackgoods(otherpid,type) {
      if(type == 1) {
        this.$router.push(this.fun.getUrl("giftIndex", { id: otherpid }));
      } else {
        this.$router.push(this.fun.getUrl("packageGoods", { id: otherpid }));
      }
    },
    //获取装修分享数据
    getShareData(data) {
      this.mainInfo = {
        name: data.share_title,
        thumb: data.share_thumb,
        introduce: data.share_desc
      };
      // this.initShare();
      this.fun.wxShare(
        "",
        {},
        {
          title: this.mainInfo.name,
          imgUrl: this.mainInfo.thumb,
          description: this.mainInfo.introduce
        },
        data => {
          // if (!this.fun.isTextEmpty(data.shop && data.shop.shop)) {
          //   this.initCservice(data.shop.shop.cservice); //客服重新赋值
          // }
        }
      );
    },
    //分享
    initShare() {
      let that = this;
      let json = {
        url:
          this.fun.isIosOrAndroid() === "android"
            ? window.location.href
            : window.initUrl,
        mid: this.fun.getKeyByMid()
      };
      $http
        .post("member.member.wxJsSdkConfig", json)
        .then(response => {
          if (response.result === 1) {
            if (response.data.config) {
              that.share(response.data);
            }
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    share(data) {
      let that = this;
      wx.config(data.config);
      wx.ready(function() {
        let _title = that.fun.isTextEmpty(that.mainInfo.name)? data.share.title : that.mainInfo.name;
        let _link = document.location.href + "&share_tag=2";
        _link = that.fun.isMid(_link, data.info.uid);
        let _imgUrl = that.fun.isTextEmpty(that.mainInfo.thumb)? data.share.icon : that.mainInfo.thumb;
        let _desc = that.fun.isTextEmpty(that.mainInfo.introduce)? data.share.desc : that.mainInfo.introduce;
        wx.showOptionMenu();
        wx.onMenuShareTimeline({
          title: _title, // 分享标题
          link: _link, // 分享链接
          imgUrl: _imgUrl, // 分享图标
          success: function() {
            Toast("分享成功");
          },
          cancel: function() {
            Toast("取消分享");
          }
        });

        wx.onMenuShareAppMessage({
          title: _title, // 分享标题
          desc: _desc, // 分享描述
          link: _link, // 分享链接
          imgUrl: _imgUrl, // 分享图标
          type: "link", // 分享类型,music、video或link，不填默认为link
          dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
          success: function() {
            Toast("分享成功");
          },
          cancel: function() {
            Toast("取消分享");
          }
        });
      });
    },
    //倒计时结束后
    salePriceTime() {
      this.limit_time_status = false;
      this.sale_priceshow = false;
      this.calculateGooss();
    },
    showGoodPup(_id) {
      if(!this.page_template) return;
      if (this.activity_gid == _id) {
        this.showgp = true;
        return;
      }
      this.activity_gid = _id;
      $http
        .get("goods.goods.get-goods-page", { id: Number(_id), is_records_history: 0}, ".")
        .then(res => {
          if (res.result == 1) {
            this.goodinfo = res.data.get_goods;
            if (res.data.get_goods.content) {
              let str = this.goodinfo.content.replace(/src=\"http:/gi, 'src="https:');
              this.goodinfo.content = str;
            } else {
              this.goodinfo.content = "暂无该商品详情";
            }
            this.$nextTick(()=>{
              this.showgp = true;
            });
          } else {
            Toast(res, msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

  },
  components: { cTitle, yzGoodsPopup,yzSpecs }
};
